import os
import json
import traceback
from util.sdk import TXrealtime
from util.sdk import Config


def requestExample(filepath):
    try:
        # 将音频文件分解成小的切片数据（即：切分成长度较小的多个字符串）发出。模拟不断发送数据接收回复，最终收完整句话的识别结果。
        # filepath = "../../test_wavs/8k.wav"
        file_object = open(filepath, 'rb')
        # file_object = voicedate
        file_object.seek(0, os.SEEK_END)
        datalen = file_object.tell()
        file_object.seek(0, os.SEEK_SET)
        # 发送请求时需要用户自行维护3个变量：voiceId：创建后保持不变； seq：递增； endFlag：前面为0，发送尾部分片的请求时设置为1
        voiceId = TXrealtime.randstr(16)
        seq = 0
        endFlag = 0
        coment = ''
        print("识别中")
        while (datalen > 0):
            if (datalen < Config.config.CUT_LENGTH):
                endFlag = 1
                content = file_object.read(datalen)
            else:
                content = file_object.read(Config.config.CUT_LENGTH)
            res = TXrealtime.sendRequest(content, voiceId, seq, endFlag)

            comentitem = res.decode("utf-8")
            itemdate = json.loads(comentitem)
            print(itemdate)
            if itemdate["code"] != 0:
                coment = "语音平台识别失败"
                break
            if itemdate["code"] == 0 and itemdate["final"] == 1:
                coment = itemdate["text"]
            seq = seq + 1
            datalen = datalen - Config.config.CUT_LENGTH

        file_object.close()
        return coment
    except Exception:
        coment = "检测通道是否联通"
        return coment